import requests
import re
from bs4 import BeautifulSoup as bs

word = 'pronunciation'
syllable = []
with open('result.txt', 'r') as f:
    for line in f:
        syllable.append(line)
bad_words = []


def craw_syllables(word):
    url = 'https://www.howmanysyllables.com/words/%s'
    r = requests.get(url % word)
    soup = bs(r.text, 'lxml')
    try:
        ans_str = soup.findAll('span', class_="Answer_Red")[1].string
        return str.split(ans_str, '-')
    except:
        print(word+'has no anwser!')
        bad_words.append(word)
        return []


def get_pronunciation(word):
    url = 'https://cn.bing.com/dict/search'
    params = {'q': word}
    r = requests.get(url, params=params)
    print(r.url)
    soup = bs(r.text, 'lxml')
    try:
        res = soup.find('div', class_='hd_prUS').string
        print(res)
        pa = '(?:\[)(.*)(?:\])'
        ans = re.search(pa,res).group(1)
        print(ans)
    except:
        print('error get pronunciation')


if __name__ == "__main__":
    get_pronunciation('syllables')


# def syllables_test():
#     out = open('result.txt', 'a')
#     with open('word_list.txt', 'r') as f:
#         for line in f:
#             print(line)
#             li = craw_syllables(str.lower(line))
#             for item in li:
#                 if (item not in syllable):
#                     syllable.append(item)
#                     out.write(item+'\n')
#     out.close()


